<?php

namespace x_mier\utils;

class Key
{
    protected $key = '';
    protected $keyShare = '';
    protected $server_public_key = '';
    protected $server_private_key = '';
    protected $client_public_key = '';
    protected $client_private_key = '';

    public function __construct()
    {
        $config = config('plugin.x_mier.doc.app');
        if ($config && !empty($config['key'])) {
            $config = $config['key'];
            $this->key = $config['key'];
            $this->keyShare = $config['keyShare'];
            $this->server_public_key = $config['server_public_key'];
            $this->server_private_key = $config['server_private_key'];
            $this->client_public_key = $config['client_public_key'];
            $this->client_private_key = $config['client_private_key'];
        }
    }
    //PHP AES PKCS7加解密
    public function encrypt($data)
    {
        $ivLength = openssl_cipher_iv_length('aes-128-cbc');
        $iv = openssl_random_pseudo_bytes($ivLength);
        $encrypted = openssl_encrypt(json_encode($data), 'aes-128-cbc', $this->key, 0, $iv);
        $rsa =  new \x_mier\utils\Rsa($this->client_public_key);
        return $rsa->publicEncrypt(base64_encode($iv)) . ',' . $encrypted; // 将IV和密文合并后base64编码
    }
    public function decrypt($data)
    {
        try {
            list($iv, $data) = explode(',', $data);
            $rsa =  new \x_mier\utils\Rsa('', $this->server_private_key);
            $iv = $rsa->privateDecrypt($iv);
            $decrypted = openssl_decrypt($data, 'aes-128-cbc', $this->key, 0, base64_decode($iv));
            if ($decrypted === false) {
            } else {
                return @json_decode($decrypted, true);
            }
        } catch (\Exception $e) {
        }
    }
    //AES加解密
    public function aesEncrypt($data, $key = null)
    {
        $encrypted = openssl_encrypt($data, 'aes-128-cbc', $key ?? $this->keyShare, 0, $key ?? $this->keyShare);
        return  base64_encode($encrypted);
    }
    public function aesDecrypt($data, $key = null)
    {
        $decrypted = openssl_decrypt(base64_decode($data), 'aes-128-cbc', $key ?? $this->keyShare, 0, $key ?? $this->keyShare);
        return @json_decode($decrypted, true);
    }
}
